package com.lagou.proxy;

import com.lagou.service.AccountService;
import com.lagou.utils.TransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author Roger
 * @date 2020/8/15 10:35
 * @description
 */
@Component
public class JDKProxyFactory {

    @Autowired
    private AccountService accountService;

    @Autowired
    private TransactionManager transactionManager;

    /*
        Class<?>[] interfaces  使用JDK代理模式要求被代理类必须继承某个接口
        InvocationHandler h
     */
    public AccountService getJDKProxy(){
        AccountService proxyInstance = (AccountService) Proxy.newProxyInstance(JDKProxyFactory.class.getClassLoader(), accountService.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object invoke = null;
                try {
                    transactionManager.startTransaction();
                    invoke = method.invoke(accountService, args);
                    transactionManager.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                    transactionManager.rollBack();
                }  finally {
                    transactionManager.release();
                }

                return invoke;
            }
        });
        return proxyInstance;
    }

}
